package Utils.db;

import Utils.UtilUtils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * DBCP工具类
 * @author d11yu
 */
public class DbcpUtils {
    private static BasicDataSource bds = null;
    private static DbcpUtils instance = null;

    /**
     * 构造函数
     *
     * @param path 配置文件路径
     */
    private DbcpUtils(String path) throws Exception {
        bds = BasicDataSourceFactory.createDataSource(UtilUtils.loadProperties(path));
    }

    /**
     * 获取实例，如果未实例化，则返回null。
     *
     * @return
     */
    public static DbcpUtils getInstance() {
        return instance;
    }

    /**
     * 获取实例，应首先调用此方法。
     *
     * @param path 配置文件路径
     * @return
     */
    public static DbcpUtils getInstance(String path) throws Exception {
        if (instance == null) {
            instance = new DbcpUtils(path);
        }
        return instance;
    }

    /**
     * 返回BasicDataSource
     *
     * @return
     */
    public BasicDataSource getBds() {
        return bds;
    }

    /**
     * 获取SQL Connection
     *
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return bds.getConnection();
    }
}
